package com.netkiller.mailmonitor.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserUtil {

	/**
	 * get current user name
	 * @return
	 */
	public static String getUserName(){
		UserService service = UserServiceFactory.getUserService();
		String userName = null;
		User user = service.getCurrentUser();
		if(user !=null){
		if(user.getNickname()!=null)
			userName= user.getNickname();
		else if(user.getUserId()!=null)
			userName = user.getUserId();
		else
			userName= user.getEmail();
		}
		return userName;
	}
	/**
	 * check if email id is valid
	 * @param email
	 * @return
	 */
	public static Boolean isValidEmail(String email){
		return email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
	}
	/**
	 * get current logged user email id
	 * @return
	 */
	public static String getEmail(){
		UserService service = UserServiceFactory.getUserService();
		User user = service.getCurrentUser();
		return user.getEmail();
	}
	
	/**
	 * get domain from mailid
	 * @param emailAddr
	 * @return
	 */
	public static String getDomain(String emailAddr){
		return emailAddr.substring( emailAddr.indexOf("@") + 1 );
	}
	
	/**
	 * get username from email
	 * @param emailAddr
	 * @return
	 */
	public static String getUserNameFromEmail(String emailAddr){
		return emailAddr.substring(0, emailAddr.indexOf("@") );
	}
	
	public static Date setDateRange(Date date, boolean dayStart) {
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(date);
		cal.set(Calendar.HOUR, 0);
		cal.set(Calendar.MINUTE, 0);
		if (!dayStart) {
			cal.add(Calendar.DATE, -5);
		}
		return cal.getTime();
	}	
}
